<template>
  <d2-container>
    <template slot="header">{{ title }}</template>
    <div style="margin-bottom:10px;font-size:14px;display:flex">
      <div style="width:95%"><span style="color:red">* </span>为必填项</div>
    </div>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">基本信息</p>
      </template>
      <el-form
        class="filter-container"
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="部门名称" prop="department_name">
              <el-select
                v-model="ruleForm.department_name"
                placeholder="请选择"
                style="width:100%;"
                :disabled="forbidden"
              >
                <el-option
                  v-for="item in selectDepartsList"
                  :key="item.department_name"
                  :label="item.name"
                  :value="item.department_name"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年度计划名称">
              <el-input
                placeholder="请输入"
                v-model="ruleForm.name"
                :disabled="forbidden"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年度计划年度">
              <el-date-picker
                v-model="ruleForm.plan_year"
                :disabled="forbidden"
                type="year"
                placeholder="选择日期时间"
                value-format="yyyy"
                style="width:100%;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="开始日期" prop="start_date">
              <el-date-picker
                v-model="ruleForm.start_date"
                type="date"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
                style="width:100%;"
                :picker-options="startDatePicker"
                :disabled="forbidden"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期" prop="end_date">
              <el-date-picker
                v-model="ruleForm.end_date"
                type="date"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
                style="width:100%;"
                :picker-options="endDatePicker"
                :disabled="forbidden"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="change_reason">
            <el-form-item label="变更原因" prop="alter_reason">
              <el-input
                placeholder="请输入"
                v-model="ruleForm.alter_reason"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="备注">
              <el-input
                class="resizeNone"
                style="width:122%"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入"
                v-model="ruleForm.remark"
                :disabled="forbidden"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">详细信息</p>
      </template>

      <el-button
        type="default"
        size="mini"
        @click.prevent="addFuturesDataRow()"
        v-show="flag"
      >
        <d2-icon name="plus" />
        增行
      </el-button>
      <el-button
        type="default"
        size="mini"
        icon="el-icon-delete"
        @click.prevent="delFuturesData()"
        v-show="flag"
      >
        删行
      </el-button>
      <div style="margin-top:15px">
        <el-form :model="tradeData" ref="futuresFrom">
          <el-table
            :data="tradeData.futuresData"
            border
            fit
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            @selection-change="futuresRow"
          >
            <el-table-column type="selection" width="40"> </el-table-column>
            <el-table-column type="index" label="序号"> </el-table-column>
            <el-table-column label="现货品种*" width="180">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.commodity'"
                  :rules="rules.commodity"
                >
                  <el-select
                    v-model="scope.row.commodity"
                    placeholder="请选择"
                    filterable
                    style="width:100%;"
                    :disabled="forbidden"
                  >
                    <el-option
                      v-for="item in selectNameList"
                      :key="item.commodity"
                      :label="item.commodity_name"
                      :value="item.commodity"
                    >
                      <span style="float: left">{{ item.commodity_name }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="统计维度*" prop="instrument" width="180">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.dimension'"
                  :rules="rules.dimension"
                >
                  <el-select
                    v-model="scope.row.dimension"
                    placeholder="请选择"
                    filterable
                    style="width:100%;"
                    :disabled="forbidden"
                  >
                    <el-option label="数量" value="0"></el-option>
                    <el-option label="金额" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="现货经营总规模*"
              prop="direction"
              width="180"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'futuresData.' + scope.$index + '.spot_management_scale'
                  "
                  :rules="rules.spot_management_scale"
                >
                  <el-input
                    type="number"
                    @keyup.native="proving2($event)"
                    v-model="scope.row.spot_management_scale"
                    placeholder="请输入"
                    :disabled="forbidden"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="现货保值总规模*"
              width="180"
              prop="offset_flag"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.spot_value_scale'"
                  :rules="rules.spot_value_scale"
                >
                  <el-input
                    type="number"
                    @keyup.native="proving2($event)"
                    v-model="scope.row.spot_value_scale"
                    placeholder="请输入"
                    :disabled="forbidden"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="期货品种*" width="220">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.product_name'"
                  :rules="rules.product_name"
                >
                  <el-select
                    v-model="scope.row.product_name"
                    placeholder="请选择"
                    filterable
                    value-key="product_id"
                    style="width:100%;"
                    @change="selectSubjectItem($event, scope.$index)"
                    :disabled="forbidden"
                  >
                    <el-option
                      v-for="item in selectProductName"
                      :key="item.product_id"
                      :label="item.product_name"
                      :value="{
                        product_name: item.product_name,
                        product_id: item.product_id
                      }"
                    >
                      <span style="float: left">{{ item.product_name }}</span>
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                        >{{ item.product_id }}</span
                      >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="套保比例*"
              prop="reference_price"
              width="180"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.hedge_ratio'"
                  :rules="rules.hedge_ratio"
                >
                  <el-input
                    type="number"
                    @keyup.native="proving2($event)"
                    v-model="scope.row.hedge_ratio"
                    placeholder="请输入"
                    :disabled="forbidden"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="保证金规模*" prop="max_volume" width="180">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.margin_scale'"
                  :rules="rules.margin_scale"
                >
                  <el-input
                    type="number"
                    @keyup.native="proving2($event)"
                    v-model="scope.row.margin_scale"
                    placeholder="请输入"
                    :disabled="forbidden"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="衍生品止损规模*"
              width="180"
              prop="derivative_stop_scale"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'futuresData.' + scope.$index + '.derivative_stop_scale'
                  "
                  :rules="rules.derivative_stop_scale"
                >
                  <el-input
                    type="number"
                    v-model="scope.row.derivative_stop_scale"
                    placeholder="请输入"
                    :disabled="forbidden"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位*" width="170" prop="unit">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.unit'"
                  :rules="rules.unit"
                >
                  <el-select
                    v-model="scope.row.unit"
                    placeholder="请选择"
                    filterable
                    style="width:100%;"
                    :disabled="forbidden"
                  >
                    <el-option label="吨" value="0"></el-option>
                    <el-option label="千克" value="1"></el-option>
                    <el-option label="桶" value="2"></el-option>
                    <el-option label="立方米" value="3"></el-option>
                    <el-option label="张" value="4"></el-option>
                    <el-option label="克" value="5"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="币种*" width="180" prop="currency">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'futuresData.' + scope.$index + '.currency'"
                  :rules="rules.currency"
                >
                  <el-select
                    v-model="scope.row.currency"
                    placeholder="请选择"
                    style="width:100%;"
                    :disabled="forbidden"
                  >
                    <el-option
                      v-for="item in selectCurrencyList"
                      :key="item.currency"
                      :label="item.currencyName"
                      :value="item.currency"
                    >
                      <span style="float: left">{{ item.currencyName }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline" v-show="his_flag">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">变更历史</p>
      </template>
      <el-table
        :data="alterDate"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        border
        highlight-current-row
      >
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="creator_name" label="变更人"></el-table-column>
        <el-table-column prop="alter_date" label="变更日期">
          <template slot-scope="scope">{{
            scope.row.alter_date | dateYMDHMSFormat
          }}</template></el-table-column
        >
        <el-table-column
          prop="alter_reason"
          label="变更原因/变更前年度计划ID"
        ></el-table-column>
      </el-table>
    </el-card>
    <el-button
      type="primary"
      size="mini"
      style="float:right;margin-left: 10px;"
      @click="submitForm('ruleForm', 'futuresFrom')"
      v-show="flag"
    >
      保存
    </el-button>
  </d2-container>
</template>

<script>
import { currency } from "@/api/url_info.js";
import { spotCommodity } from "@/api/url_info.js";
import { getDepartments } from "@/api/url.js";
import { editAnnualPlan } from "@/api/url_info.js";
import { annualPlan } from "@/api/url_info.js";
import { annualPlanAlter } from "@/api/url_info.js";
import { futureCommodity } from "@/api/url_info.js";
export default {
  //年度计划-编辑
  name: "annual_plan_edit",
  components: {},
  data() {
    return {
      historicalApprovals: false,
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      selectCurrencyList: [],
      selectNameList: [],
      selectDepartsList: [],
      selectProductName: [],
      state: "",
      title: "",
      strategy_count: null,
      alterDate: null,
      flag: true,
      info_flag: true,
      forbidden: false,
      change_info: false,
      change_reason: false,
      his_flag: false,
      ruleForm: {},
      tradeData: {
        futuresData: []
      },
      futureslistRow: [],
      futuresNum: 1,
      rules: {
        alter_reason: [
          { required: true, message: "请输入变更原因", trigger: "blur" }
        ],
        department: [
          { required: true, message: "请选择部门名称", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入年度计划名称", trigger: "blur" }
        ],
        plan_year: [
          { required: true, message: "请选择年度计划年度", trigger: "change" }
        ],
        start_date: [
          {
            required: true,
            message: "请选开始日期",
            trigger: "change"
          }
        ],
        end_date: [
          {
            required: true,
            message: "请选择结束日期",
            trigger: "change"
          }
        ],

        commodity: [
          { required: true, message: "请选择品种", trigger: "change" }
        ],
        dimension: [
          { required: true, message: "请选择统计维度", trigger: "change" }
        ],
        spot_management_scale: [
          { required: true, message: "请输入现货经营总规模", trigger: "blur" }
        ],
        spot_value_scale: [
          { required: true, message: "请输入现货保值总规模", trigger: "blur" }
        ],
        hedge_ratio: [
          { required: true, message: "请输入套保比例", trigger: "blur" }
        ],
        margin_scale: [
          { required: true, message: "请输入保证金规模", trigger: "blur" }
        ],
        derivative_stop_scale: [
          { required: true, message: "请输入衍生品止损规模", trigger: "blur" }
        ],
        unit: [{ required: true, message: "请选择单位", trigger: "change" }],
        currency: [
          { required: true, message: "请选择币种", trigger: "change" }
        ],
        product_name: [
          { required: true, message: "请选择期货品种", trigger: "change" }
        ]
      },
      instrumentVisible: false,
      instrumentRow: null
    };
  },
  created() {
    this.His();
    this.handle_currencyChange();
    this.handle_spotCommodity();
    this.handle_getDepartments();
    this.handle_futureCommodity();
  },
  methods: {
    //禁止输入负数
    proving2(e) {
      var keynum = window.event ? e.keyCode : e.which; //获取键盘码
      var keychar = String.fromCharCode(keynum); //获取键盘码对应的字符
      if (keynum == 189 || keynum == 109) {
        this.$message.warning("禁止输入负数");
        e.target.value = "";
      }
    },

    //树形结构转换为扁平数组
    treeToList(tree) {
      var queen = [];
      var out = [];
      queen = queen.concat(tree);
      while (queen.length) {
        var first = queen.shift();
        if (first.sub_depart) {
          queen = queen.concat(first.sub_depart);
          delete first["sub_depart"];
        }
        out.push(first);
      }
      return out;
    },
    // 查询币种
    handle_currencyChange() {
      currency()
        .then(res => {
          this.selectCurrencyList = [];
          var data1 = res.result.results;
          for (var i = 0; i < data1.length; i++) {
            this.selectCurrencyList[i] = {
              currencyName: data1[i]["name"],
              currency: data1[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 查询期货品名
    handle_spotCommodity() {
      spotCommodity()
        .then(res => {
          this.selectNameList = [];
          var data = res.result.results;
          for (var i = 0; i < data.length; i++) {
            this.selectNameList[i] = {
              commodity_name: data[i]["name"],
              commodity: data[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 查询部门
    handle_getDepartments() {
      getDepartments()
        .then(res => {
          this.selectDepartsList = [];
          var data1 = res.result;
          var arr = this.treeToList(data1);
          for (var i = 0; i < arr.length; i++) {
            this.selectDepartsList[i] = {
              name: arr[i]["name"],
              department_name: arr[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //网格信息
    annualPlan() {
      annualPlan({ id: this.$route.query.id })
        .then(res => {
          let data = res.result.results[0],
            info = res.result.results[0].annual_plan_details_info,
            spotDatas = [];
          this.ruleForm = data;
          if (this.ruleForm.org_name == null) {
            this.ruleForm.org_name = this.ruleForm.department_name;
          }
          for (let i = 0; i < info.length; i++) {
            spotDatas[i] = {
              annual_plan: info[i]["annual_plan"],
              commodity: info[i]["commodity"],
              created_time: info[i]["created_time"],
              derivative_stop_scale: info[i]["derivative_stop_scale"],
              dimension: info[i]["dimension"].toString(),
              hedge_ratio: info[i]["hedge_ratio"],
              id: info[i]["id"],
              margin_scale: info[i]["margin_scale"],
              modified_time: info[i]["modified_time"],
              spot_management_scale: info[i]["spot_management_scale"],
              spot_value_scale: info[i]["spot_value_scale"],
              currency: info[i]["currency"],
              product_name: info[i]["product_name"],
              product_id: info[i]["product_id"],
              unit: info[i]["unit"].toString()
            };
          }
          this.tradeData.futuresData = spotDatas;
          if (this.$route.query.state === "check") {
            this.title = "年度计划-查看";
            if (this.ruleForm.status == "已失效") {
              this.change_info = true;
            }
            this.forbidden = true;
            this.flag = false;
            this.his_flag = true;
          } else if (this.$route.query.state === "alter") {
            this.title = "年度计划-修改";
            this.info_flag = false;
            this.his_flag = false;
          } else if (this.$route.query.state === "copy") {
            this.title = "年度计划-复制";
            this.info_flag = false;
            this.his_flag = false;
          } else if (this.$route.query.state === "change") {
            this.title = "年度计划-变更";
            this.change_reason = true;
            this.his_flag = false;
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 查询期货品名
    handle_futureCommodity() {
      futureCommodity({ type: "futures" })
        .then(res => {
          this.selectProductName = [];
          var data1 = res.result;
          for (var i = 0; i < data1.length; i++) {
            this.selectProductName[i] = {
              product_id: data1[i]["productID"],
              product_name: data1[i]["productName"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    selectSubjectItem(event, index) {
      [this.tradeData.futuresData[index]].forEach(item => {
        item.product_id = event.product_id;
        item.product_name = event.product_name;
      });
      console.log("12312", this.tradeData.futuresData);
    },
    //审批历史弹框
    historicalApproval(row) {
      this.$router.push("/examine_historyss?id=" + this.ruleForm.workOrderID);
    },
    //查询变更历史
    async His() {
      this.annualPlan();
      let datas = { id: this.$route.query.id };
      let alterDates = [];
      await annualPlanAlter(datas)
        .then(res => {
          let data = res.result;
          for (let i = 0; i < data.length; i++) {
            alterDates[i] = {
              alter_date: data[i]["alter_date"],
              alter_reason: data[i]["alter_reason"],
              creator_name: data[i]["creator_name"]
            };
          }
          this.alterDate = alterDates;
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //这里是控制结束日期不能小于开始日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.ruleForm.end_date) {
            //如果结束时间不为空，则小于结束时间
            return new Date(self.ruleForm.end_date).getTime() < time.getTime();
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.ruleForm.start_date) {
            //如果开始时间不为空，则结束时间大于开始时间
            return (
              new Date(self.ruleForm.start_date).getTime() >
              time.getTime() + 8.64e7
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    //保存
    async submitForm(formName, futuresName) {
      let params = {};
      if (this.$route.query.state === "alter") {
        params = {
          operation: "MOD",
          //基础信息
          plan_info: this.ruleForm,
          //交易信息
          plan_details: this.tradeData.futuresData
        };
      } else if (this.$route.query.state === "copy") {
        [this.ruleForm].forEach(item => {
          item.status = "0";
        });
        params = {
          operation: "ADD",
          //基础信息
          plan_info: this.ruleForm,
          //交易信息
          plan_details: this.tradeData.futuresData
        };
      } else if (this.$route.query.state === "change") {
        [this.ruleForm].forEach(item => {
          item.status = "0";
        });
        params = {
          operation: "STATUS",
          //基础信息
          plan_info: this.ruleForm,
          //交易信息
          plan_details: this.tradeData.futuresData
        };
      }
      const rule1 = new Promise((resolve, reject) => {
        this.$refs[formName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      const rule3 = new Promise((resolve, reject) => {
        this.$refs[futuresName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      Promise.all([rule1, rule3]).then(() => {
        editAnnualPlan(params)
          .then(res => {
            this.$message({
              message: res.result,
              type: "success"
            });
            this.closeing.closePage(
              this.$store.getters["d2admin/page/allPage"],
              this.$store.getters["d2admin/page/currentPage"]
            );
            this.$router.push({
              path: "/annual_plan/plan_index"
            });
          })
          .catch(err => {
            this.$message.error(err.msg);
          });
      });
    },
    // 获取表格选中时的数据
    futuresRow(val) {
      this.futureslistRow = val;
    },
    // 删除选中行
    delFuturesData() {
      let val = this.futureslistRow;
      if (val.length > 0) {
        for (let i = 0; i < this.futureslistRow.length; i++) {
          val.forEach((val, index) => {
            this.tradeData.futuresData.forEach((v, i) => {
              if (val.id === v.id) {
                this.tradeData.futuresData.splice(i, 1);
              }
            });
          });
        }
        this.$refs.table.clearSelection();
      } else {
        this.$message({
          type: "warning",
          message: "请选择删除数据"
        });
      }
    },

    // 增加行
    addFuturesDataRow() {
      var list = {
        futuresNum: this.futuresNum,
        commodity: "",
        dimension: "",
        spot_management_scale: "",
        spot_value_scale: "",
        hedge_ratio: "",
        margin_scale: "",
        derivative_stop_scale: "",
        unit: "",
        currency: "",
        id: "",
        product_name: "",
        product_id: ""
      };
      this.tradeData.futuresData.unshift(list);
      this.futuresNum += 1;
    }
  }
};
</script>
<style lang="scss" scoped>
.resizeNone {
  .el-textarea__inner {
    resize: none;
  }
}
.el-form-item {
  margin-bottom: 0px !important;
}
</style>
